package com.hfzy.ihk.web.linkcall.biz.flow.config;

import com.hfzy.ihk.common.core.elasticsearch.EsQueryUtils;
import com.hfzy.ihk.common.core.elasticsearch.service.EsBaseServiceImpl;
import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.CustomerAnswerWay;
import com.hfzy.ihk.web.linkcall.dao.CustomerAnswerWayRepository;
import com.hfzy.ihk.web.linkcall.support.annotation.PreProcessParam;
import com.hfzy.ihk.web.linkcall.support.annotation.PushMsgToAIService;
import com.hfzy.ihk.web.linkcall.utils.UserUtils;
import com.hfzy.ihk.web.linkcall.utils.WebResultUtils;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Component
public class CustomerAnswerWayBiz extends EsBaseServiceImpl<CustomerAnswerWay> {
    @Autowired
    CustomerAnswerWayRepository customerAnswerWayRepository;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;


    @Override
    protected ElasticsearchCrudRepository getReposity() {
        return customerAnswerWayRepository;
    }

    @PushMsgToAIService
    public WebResult addCustomerAnswerWay(CustomerAnswerWay customerAnswerWay) {
        WebResult webResult = null;
        customerAnswerWay.setCreateTime(new Date());
        customerAnswerWay.setModTime(new Date());
        customerAnswerWay.setId(UUIDs.base64UUID());
        customerAnswerWay.setTypeKey("custom_"+customerAnswerWay.getId());
        customerAnswerWay.setCreateUserId(UserUtils.getCurrentUserId()!=null?UserUtils.getCurrentUserId():0L);
        customerAnswerWayRepository.save(customerAnswerWay);
        webResult = WebResultUtils.getSuccessCharWebResult("", 0, null);
        return webResult;
    }

    @PreProcessParam
    public Page<CustomerAnswerWay> getCustomerAnswerWayByPage(Map<String, String> params) {
        BoolQueryBuilder boolQueryBuilder = getQueryBuilderByParams(params);
        int pageNum = Integer.valueOf(params.get("page")) - 1;
        int pageSize = Integer.valueOf(params.get("pageSize"));
        //添加排序字段
        FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort("createTime").order(SortOrder.DESC);
        return getCustomerAnswerWayPageByCondition(pageNum, pageSize, boolQueryBuilder, fieldSortBuilder);
    }

    @PreProcessParam
    public List<CustomerAnswerWay> getCustomerAnswerWayList(Map<String, String> params) {
        List<CustomerAnswerWay> customerAnswerWays = null;
        BoolQueryBuilder boolQueryBuilder = getQueryBuilderByParams(params);
        Iterator<CustomerAnswerWay> iterator = customerAnswerWayRepository.search(boolQueryBuilder).iterator();
        if (iterator != null) {
            customerAnswerWays = new ArrayList<CustomerAnswerWay>();
            while (iterator.hasNext()) {
                CustomerAnswerWay next = iterator.next();
                customerAnswerWays.add(next);
            }
        }
        return customerAnswerWays;

    }


    public CustomerAnswerWay getCustomerAnswerWayById(String id) {
        Map params = new HashMap();
        params.put("id", id);
        List<CustomerAnswerWay> customerAnswerWays = getCustomerAnswerWayList(params);
        return Utils.getFirst(customerAnswerWays);
    }


    public BoolQueryBuilder getQueryBuilderByParams(Map<String, String> params) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        Iterator entries = params.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            String key = entry.getKey().toString();
            switch (key) {
                case "packageName":
                    if(StringUtil.isNotNull(params.get("packageName"))){
                        QueryBuilder projectName = EsQueryUtils.wildcardQuery("packageName", "*" + params.get("packageName") + "*");
                        EsQueryUtils.boolQuery(boolQueryBuilder, EsQueryUtils.BoolType.MUST, projectName);
                    }
                    break;
                case "id":
                    QueryBuilder queryBuilder = EsQueryUtils.termQuery("id", params.get("id"));
                    boolQueryBuilder.must(queryBuilder);
                    break;
                case "flowStepId":
                    boolQueryBuilder.must(EsQueryUtils.termQuery("flowStepId", params.get("flowStepId")));
                    break;
                case "flowId":
                    boolQueryBuilder.must(EsQueryUtils.termQuery("flowId", params.get("flowId")));
                    break;
                case "createUserId":
                    boolQueryBuilder.must(EsQueryUtils.termQuery("createUserId", params.get("createUserId")));
                    break;
                default:
                    break;
            }
        }
        return boolQueryBuilder;
    }

    public Page<CustomerAnswerWay> getCustomerAnswerWayPageByCondition(int pageNum, int pageSize, BoolQueryBuilder boolQueryBuilder, FieldSortBuilder fieldSortBuilder) {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(fieldSortBuilder).withPageable(PageRequest.of(pageNum, pageSize));
        return customerAnswerWayRepository.search(builder.build());
    }

    @PushMsgToAIService
    public WebResult saveCustomerAnswerWay(CustomerAnswerWay customerAnswerWay) {
        WebResult webResult = null;
        Date date = new Date();
        if (!Utils.isNullString(customerAnswerWay.getId())) {
            customerAnswerWay.setModTime(date);
            customerAnswerWayRepository.save(customerAnswerWay);
        } else {
            webResult = WebResultUtils.getFailCharWebResult("参数异常");
        }
        webResult = WebResultUtils.getSuccessCharWebResult("", 0, null);
        return webResult;
    }

    @PushMsgToAIService
    public WebResult deleteCustomerAnswerWayById(String id) {
        WebResult webResult = null;
        try{
            customerAnswerWayRepository.deleteById(id);
            webResult = WebResultUtils.getSuccessCharWebResult("", 0, null);
        }catch (Exception e){
            webResult = WebResultUtils.getExceptionCharWebResult(e.getMessage());
        }finally {
            if(webResult == null){
                webResult = WebResultUtils.getFailCharWebResult("");
            }
        }
        return webResult;
    }

    public List<CustomerAnswerWay> getCustomerAnswerWayByFlowStepId(String flowStepId) {
        Map params = new HashMap();
        params.put("flowStepId", flowStepId);
        List<CustomerAnswerWay> customerAnswerWays = getCustomerAnswerWayList(params);
        return  customerAnswerWays;
    }

    /**
     * 获取流程默认的分支
     * */
    public List<CustomerAnswerWay> getFlowDefalutCustomerAnswerWay(String flowId) {
        Map params = new HashMap();
        params.put("flowId", flowId);
        params.put("flowStepId", "0");
        List<CustomerAnswerWay> customerAnswerWays = getCustomerAnswerWayList(params);
        return  customerAnswerWays;
    }

    /**
     * 获取默认的分支
     * */
    public List<CustomerAnswerWay> getDefalutCustomerAnswerWay() {
        Map params = new HashMap();
        params.put("flowId", "0");
        params.put("flowStepId", "0");
        List<CustomerAnswerWay> customerAnswerWays = getCustomerAnswerWayList(params);
        return  customerAnswerWays;
    }

}
